package com.example.secondhandshop.utils;



import android.content.Context;
import android.content.SharedPreferences;

import com.example.secondhandshop.bean.User;

public class UserManagerUtil {
    private static final String SP_FILE_NAME = "user_prefs";
    private static final String KEY_APP_KEY = "appKey";
    private static final String KEY_AVATAR = "avatar";
    private static final String KEY_ID = "id";
    private static final String KEY_MONEY = "money";
    private static final String KEY_USERNAME = "username";

    private SharedPreferences sharedPreferences;

    public UserManagerUtil(Context context) {
        sharedPreferences = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
    }

    public void saveUser(User user) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_APP_KEY, user.getAppKey());
        editor.putString(KEY_AVATAR, user.getAvatar());
        editor.putLong(KEY_ID, user.getId());
        editor.putInt(KEY_MONEY, user.getMoney());
        editor.putString(KEY_USERNAME, user.getUsername());
        editor.apply();
    }

    public User getUser() {
        User user = new User();
        user.setAppKey(sharedPreferences.getString(KEY_APP_KEY, null));
        user.setAvatar(sharedPreferences.getString(KEY_AVATAR, null));
        user.setId(sharedPreferences.getLong(KEY_ID, -1));
        user.setMoney(sharedPreferences.getInt(KEY_MONEY, 0));
        user.setUsername(sharedPreferences.getString(KEY_USERNAME, null));
        return user;
    }

    public boolean isUserLoggedIn() {
        return sharedPreferences.contains(KEY_APP_KEY); // 根据 appKey 检查用户是否已登录
    }

    public void clearUser() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
    }
}
